#!/bin/bash
# ================================================
# 缤纷云对象存储卸载脚本
# 功能：卸载bitifs客户端，清理挂载、配置和服务
# 版本: 2.1
# 更新: 适配新安装脚本的配置
# ================================================

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 彩色输出函数
info() { echo -e "${GREEN}[信息]${NC} $1"; }
warn() { echo -e "${YELLOW}[警告]${NC} $1"; }
error() { echo -e "${RED}[错误]${NC} $1"; exit 1; }
title() { echo -e "${BLUE}$1${NC}"; }

# 检查root权限
[ "$(id -u)" != "0" ] && error "此脚本需要root权限执行!"

# 欢迎信息
title "================================================"
title "  缤纷云(bitiful.com)对象存储卸载脚本"
title "================================================"
info " 功能说明:"
info " 1. 停止并禁用bitifs挂载服务"
info " 2. 卸载对象存储挂载点"
info " 3. 删除bitifs客户端程序"
info " 4. 清理AK/SK凭证配置"
info " 5. 可选删除挂载目录"
warn ""
warn " 注意: 此操作将永久删除以下内容:"
warn " 1. /usr/local/bin/bitifs (客户端程序)"
warn " 2. /etc/bitifs/ (凭证配置)"
warn " 3. 挂载服务配置"
warn ""
warn " 操作前请确保:"
warn " 1. 已备份挂载点中的重要数据"
warn " 2. 已关闭所有访问挂载点的程序"
title "================================================"

# 确认卸载
read -p "$(info '确定要卸载bitiful对象存储吗？(y/n): ')" confirm
[ "$confirm" != "y" ] && exit 0

# 获取挂载点信息
MOUNT_PATH=$(systemctl cat bitifs-mount.service 2>/dev/null | grep -oP 'ExecStart.*\s\K\/\S+' | head -1)
MOUNT_PATH=${MOUNT_PATH:-"/mnt/bitiful-oss"}
BUCKET_NAME=$(systemctl cat bitifs-mount.service 2>/dev/null | grep -oP 'bitifs\s+\K\S+' | head -1)

# 停止并禁用服务
info "停止并禁用bitifs挂载服务..."
systemctl stop bitifs-mount.service 2>/dev/null
systemctl disable bitifs-mount.service 2>/dev/null
rm -f /etc/systemd/system/bitifs-mount.service
systemctl daemon-reload
systemctl reset-failed 2>/dev/null

# 卸载挂载点
info "卸载挂载点..."
if mount | grep -q "$MOUNT_PATH"; then
    umount -l "$MOUNT_PATH" 2>/dev/null || \
    warn "卸载挂载点失败，可能是已被卸载或挂载点不存在"
else
    info "挂载点 $MOUNT_PATH 未挂载"
fi

# 清理文件和目录
info "清理bitifs相关文件和配置..."
rm -f /usr/local/bin/bitifs 2>/dev/null
rm -rf /etc/bitifs 2>/dev/null

# 删除挂载目录（可选）
if [ -d "$MOUNT_PATH" ]; then
    read -p "$(info "是否删除挂载目录 $MOUNT_PATH？(y/n): ")" delete_dir
    if [ "$delete_dir" = "y" ]; then
        rm -rf "$MOUNT_PATH" && info "已删除挂载目录 $MOUNT_PATH" || \
        warn "删除挂载目录失败，可能是权限不足"
    fi
fi

# 清理残留进程
info "清理残留进程..."
pkill -f "bitifs $BUCKET_NAME" 2>/dev/null && warn "已终止残留的bitifs进程"

# 完成信息
title "================================================"
info "卸载完成!"
info ""
info "已清理以下内容:"
info "1. bitifs-mount.service 服务"
info "2. /usr/local/bin/bitifs 客户端"
info "3. /etc/bitifs/ 配置目录"
[ "$delete_dir" = "y" ] && info "4. 挂载目录 $MOUNT_PATH"
info ""
info "如需重新安装，请运行安装脚本: install-bitiful-oss.sh"
title "================================================"